package com.chiancloud.shield.core.main;

import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.io.IOException;


@SuppressWarnings("UseOfSunClasses")
public final class IrqHandler implements SignalHandler {

  public static final String CONTROL_C = "INT";
  public static final String SIGTERM = "TERM";

  private final String name;
  private final Interrupted handler;

  public IrqHandler(String name, Interrupted handler) throws IOException {
    this.handler = handler;
    this.name = name;
    try {
      Signal.handle(new Signal(name), this);
    } catch (IllegalArgumentException e) {
      throw new IOException(
        "Could not set handler for signal \"" + name + "\"."
        + "This can happen if the JVM has the -Xrs set.",
        e);
    }
  }

  @Override
  public String toString() {
    return "IrqHandler for signal " + name ;
  }

//  @Override
  public void handle(Signal signal) {
    InterruptData data = new InterruptData(signal.getName(), signal.getNumber());
    handler.interrupted(data);
  }

  public static class InterruptData {
    public final String name;
    public final int number;

    public InterruptData(String name, int number) {
      this.name = name;
      this.number = number;
    }

    @Override
    public String toString() {
      return "signal " + name + '(' + number + ')';
    }
  }

  public interface Interrupted {

    void interrupted(InterruptData interruptData);
  }
}